/**
 * Created by amarsoft on 2017/11/1.
 */

(function (global) {
  var activeItemElement = null
  var vm = null
  var scope = {}
  scope.menuDataChild = null;
  scope.width = {
    //当前位置
    point: 0,
    //滑动窗口大小
    window: 400,
    //itemsWidth:菜单总宽度
    //contWidth:导航栏宽度
  };
  //当前一级菜单子选项索引
  scope.currItemIndex = 0;
  //左右滑动按钮状态
  scope.leftActive = 0;
  scope.rightActive = 0;
  //三级菜单弹出按钮状态
  scope.isCollapse = 0;
  //.rb-nav-menu-wrapper宽度
  scope.panelWidth = 0;

  $('#rb-nav-slip-right').removeClass('rb-nav-slip-active').addClass('rb-nav-slip-hidden')
  $('#rb-nav-slip-left').removeClass('rb-nav-slip-active').addClass('rb-nav-slip-hidden')

  $(window).resize(function () {
    slipResize()
  })

  function pDMenuPosiAutoAdapt (elem) {
    //主导航内容
    var pElem = $('.rb-nav-menu-wrapper');
    //弹出菜单内容
    var cElem = $('.rb-nav-pulldown');
    //左滑动按钮
    var sElem = $('#rb-nav-slip-left');
    //弹出菜单中的二级菜单项内容
    var section = $('.rb-nav-menu-subcontent');
    //弹出菜单盒模型padding+margin大小
    var boxOffset = parseInt(cElem.css('padding-left')) * 2
      + parseInt(cElem.css('margin-left')) * 2;
    //计算总高度
    var sumHeight = function(array, cols){
      var height = 0;
      var sum = 0;
      // console.log(array.length/cols,array.length%cols)
      var rows = array.length%cols==0?array.length/cols:parseInt(array.length/cols)+1;
      for(var i=0;i<rows;i++){
        for(var j=0;j<cols && i*cols+j<array.length;j++){
          if(array[i*cols+j]>height){
            height = array[i*cols+j];
          }
        }
        sum += height;
      }
      return sum;
    }
    //单个二级菜单内容宽度大于主导航内容的情况
    if (section.outerWidth() + boxOffset > pElem.outerWidth() - sElem.outerWidth() * 2) {
      return;
    }
    //左右边界
    var LeftBand = parseInt(pElem.offset().left + sElem.outerWidth());
    var RightBand = parseInt(pElem.offset().left + pElem.outerWidth() - sElem.outerWidth());
    //距离左右边界
    var toLeft = parseInt(elem.offset().left - LeftBand + elem.outerWidth() / 2);
    var toRight = parseInt(pElem.outerWidth() - sElem.outerWidth() * 2 - toLeft);
    //初始化靠左位置
    var left = LeftBand;
    //二级菜单内容总宽度
    var sumWidth = 0;
    //存储二级菜单高度
    var secHeight = [];
    //计算总宽度；三级菜单位置左对齐于二级菜单第一个字
    for (var i = 0; i < section.length; i++) {
      sumWidth += $(section[i]).outerWidth();
      //获取二级菜单高度
      secHeight.push($(section[i]).outerHeight());
      var sec = $(section[i]).find('.sec-level-item').find('a').find('label').position().left - $(section[i]).find('.sec-level-item').position().left;
      $(section[i]).find('.sub-rb-nav-menu-subcontent').css('padding-left', sec + 'px');
    }
    //总宽度要加上盒模型宽度
    sumWidth += boxOffset;
    //自适应的列数、行数
    var nCol = 0;
    var nRow = 0;
    //行最大可容纳的列数
    var nSinLine = parseInt(pElem.outerWidth() / $('.mega-menu-content').outerWidth());

    //弹出菜单宽度是否大于主导航宽度
    //根据一级菜单相对于左右边界的位置和弹出菜单宽度可分为两种情况：
    // （1）小于时可分为三种情况：1，适合居中对齐；2，适合左对齐；3，适合右对齐
    // （2）大于时设置弹出菜单最大宽度为最大可容纳二级菜单内容的宽度，由于最大宽度可能小于主导航宽度，
    //因此又可以分为三种情况，同小于主导航宽度的情形
    if (sumWidth > RightBand - LeftBand) {
      nCol = nSinLine;
      // nRow = section.length % nCol > 0 ?parseInt(section.length / nCol+1) : parseInt(section.length / nCol+1);
      // if(maxHeight(secHeight)>cElem.outerHeight()){
      //     sumWidth += 10;
      // }
      var sumWidth = RightBand - LeftBand - (RightBand - LeftBand - boxOffset) % $('.mega-menu-content').outerWidth();
      //给滚动条腾出位置
      if(sumHeight(secHeight, nCol)>cElem.outerHeight()){
        sumWidth+=18;
      }
      cElem.css('max-width', sumWidth + 'px');
      //解决浏览器宽度加大时，弹出菜单没有跟随一级菜单项的bug
      cElem.css('width', sumWidth + 'px');
      if (sumWidth / 2 <= toLeft && sumWidth / 2 <= toRight) {
        cElem.css('left', left + toLeft - sumWidth / 2 + 'px');
      }
      else if (sumWidth / 2 < toLeft && sumWidth / 2 > toRight) {
        cElem.css('left', RightBand - sumWidth + 'px');
      }
      else if (sumWidth / 2 < toRight && sumWidth / 2 > toLeft) {
        cElem.css('left', left + 'px');
      }
      else {
        // console.log('bug');
      }
    }
    else {
      nCol = (sumWidth - boxOffset) / $('.mega-menu-content').outerWidth();
      nRow = 1;

      //给滚动条腾出位置
      if(sumHeight(secHeight, nCol)>cElem.outerHeight()){
        sumWidth+=18;
      }
      //解决浏览器宽度加大时，弹出菜单没有跟随一级菜单项的bug
      if (cElem.outerWidth() != sumWidth) {
        cElem.css('width', sumWidth + 'px');
      }
      if (sumWidth / 2 <= toLeft && sumWidth / 2 <= toRight) {
        cElem.css('left', left + toLeft - sumWidth / 2 + 'px');
      }
      else if (sumWidth / 2 < toLeft && sumWidth / 2 > toRight) {
        cElem.css('left', RightBand - sumWidth + 'px');
      }
      else if (sumWidth / 2 < toRight && sumWidth / 2 > toLeft) {
        cElem.css('left', left + 'px');
      }
      else {
        // console.log('bug');
      }
      // console.log('consider 2',cElem.outerWidth())
    }
    /*var maxBorderHeight = 0;
    for (var i = 0; i < nRow; i++) {
      var cols = (i == nRow - 1) ? section.length : (i + 1) * nSinLine;
      for (var j = i * nSinLine; j < cols; j++) {
        var height = $(section[j]).find('.sub-mega-menu-content').outerHeight();
        if (height >= maxBorderHeight) {
          maxBorderHeight = height;
        }
      }
      for (var k = i * nSinLine; k < j; k++) {
        var n = k - i * nSinLine;
        var subs = $(section[k]).find('.sub-mega-menu-content');
        $(children[k]).children().css('padding-left', offset + 'px');

        /!*绘制分隔线，不要删除此注释！！！*!/
        subs.css('height', maxBorderHeight + 'px');
        if (k > i * nSinLine) {
          subs.css('border-left', '1px solid #bbb');
        }
      }
    }*/
  }

  function slipResize () {
    scope.width.contWidth = $('.rb-nav-menu-wrapper').outerWidth();
    if (scope.width.point + scope.width.contWidth >= scope.width.itemsWidth) {
      scope.width.point = scope.width.itemsWidth - scope.width.contWidth;
      $('.rb-nav-container').css('left', -scope.width.point + 'px');
      $('#rb-nav-slip-right').removeClass('rb-nav-slip-active').addClass('rb-nav-slip-hidden')
      // scope.rightActive = 0;
    }
    else {
      $('#rb-nav-slip-right').addClass('rb-nav-slip-active').removeClass('rb-nav-slip-hidden')
      // scope.rightActive = 1;
    }
    if (scope.width.point < 0) {
      scope.width.point = 0;
      $('.rb-nav-container').css('left', scope.width.point + 'px');
      $('#rb-nav-slip-left').removeClass('rb-nav-slip-active').addClass('rb-nav-slip-hidden')
      // scope.leftActive = 0;
    }
  }

  function rendMenuItem(menuData, container) {
    container = container || $('#rb-nav-menu-container')
    if (!(container && container.length)) {
      console.error('找不到渲染容器');
      return;
    }

    if (!menuData || !menuData instanceof Array) {
      console.error('渲染菜单列表数据格式出错');
      return;
    }

    scope.menuData = menuData

    menuData.forEach(function (menuItem, index) {
      rend(menuItem)
    })

    scope.width.itemsWidth = container.outerWidth();
    scope.width.contWidth = container.parent().outerWidth();
    slipResize()

    $('#rb-nav-slip-left').click(function () {
      // console.log('left')
      var moveDistance = parseInt(container.css('left'));
      // scope.rightActive = 1;
      $('#rb-nav-slip-right').addClass('rb-nav-slip-active').removeClass('rb-nav-slip-hidden')
      // console.log(scope.width)
      if (scope.width.point >= 0 && scope.width.point <= scope.width.itemsWidth - scope.width.contWidth) {
        if (scope.width.window < scope.width.point) {
          scope.width.point -= scope.width.window;
          moveDistance += scope.width.window;
        }
        else {
          scope.width.point = 0;
          moveDistance = -scope.width.point;
          setTimeout(function () {
            // scope.leftActive = 0;
            $('#rb-nav-slip-left').removeClass('rb-nav-slip-active').addClass('rb-nav-slip-hidden')
          }, 500);
        }
        container.css('left', moveDistance + 'px');
      }
    })

    $('#rb-nav-slip-right').click(function () {
      // console.log('right')
      //左滑动按钮激活
      // scope.leftActive = 1;
      $('#rb-nav-slip-left').addClass('rb-nav-slip-active').removeClass('rb-nav-slip-hidden')
      //指针范围
      // console.log(scope.width)
      if (scope.width.point >= 0 && scope.width.point < scope.width.itemsWidth - scope.width.contWidth) {
        //滑动距离，如果剩余距离大小小于窗口距离，则滑动当前距离大小
        var moveDistance = parseInt(container.css('left'));
        if (scope.width.point >= 0 && scope.width.point <= scope.width.itemsWidth - scope.width.contWidth) {
          if (scope.width.window < scope.width.itemsWidth - scope.width.contWidth - scope.width.point) {
            scope.width.point += scope.width.window;
            moveDistance -= scope.width.window;
          }
          else {
            scope.width.point = scope.width.itemsWidth - scope.width.contWidth;
            moveDistance = -scope.width.point;
            setTimeout(function () {
              //距离右边距为0，关闭右按钮
              // scope.rightActive = 0;
              $('#rb-nav-slip-right').removeClass('rb-nav-slip-active').addClass('rb-nav-slip-hidden')
            }, 500);
          }
          // console.warn(container)
          container.css('left', moveDistance + 'px');
        }
      }
    })

    $('#rb-nav-pulldown-container').hover(function () {
      $('.rb-nav-menu-item', container).removeClass('active');
      activeItemElement && activeItemElement.addClass('active');
    }, function () {
      removePDMenuItem();
    })

    function rend(menuItem) {
      //rb-nav-menu-item
      var _li =
        '<li class="rb-nav-menu-item" load-item-by-item>\n' +
        '    <span class="active-hover"></span>\n' +
        '    <a href="javascript:void(0);">\n' +
        '        <span class="icon-wrap">\n' +
        (menuItem.icon ? '             <i></i>\n' : '\n') +
        '        </span>\n' +
        '        <span><label></label></span>\n' +
        '    </a>\n' +
        '</li>';

      _li = $(_li)
      _li.hover(function () {
        $('.rb-nav-menu-item', container).removeClass('active');
        _li.addClass('active')
        if (activeItemElement === _li)return
        activeItemElement = _li
        $('#rb-nav-pulldown-container').html('');
        rendPDMenuItem(menuItem)
      }, function () {
        _li.removeClass('active')
        removePDMenuItem()
      })
      var _lia = $('a', _li)
      _lia.click(function () {
        selectMegaMenuItem(menuItem)
      })
      $('i', _lia).addClass(menuItem.icon)
      $('label', _lia).html(menuItem.name)
      container.append(_li)
    }

  }

  function removePDMenuItem(container) {
    setTimeout(function(){
      container = container || $('#rb-nav-pulldown-container')
      // console.log(!container.is(':hover'), !(activeItemElement && activeItemElement.is(':hover')))
      if (!container.is(':hover') && !(activeItemElement && activeItemElement.is(':hover'))) {
        container.html('');
        container.hide();
        if(!activeItemElement)return;
        activeItemElement.removeClass('active')
        activeItemElement = null
      }
    })
  }

  function rendPDMenuItem(menuItem, container) {
    container = container || $('#rb-nav-pulldown-container')
    if (!(container && container.length)) {
      console.error('找不到渲染容器');
      return;
    }

    if (!menuItem || !menuItem instanceof Object) {
      console.error('渲染菜单项数据格式出错');
      return;
    }

    treenavIterator(menuItem, function(item, level, index, order){
      // 记录menuItem回溯顺序
      if(!item._family){
        var _family = order.clone()
        _family.unshift(scope.menuData.indexOf(menuItem))
        item._family = _family;
      }
      rendUl(item, level, index, order)
    })
    container.children() && container.children().length && container.show();
    pDMenuPosiAutoAdapt(activeItemElement)
    function rendUl(menuItem, level, index, order) {
      var ul = null
      if (level === 0) {
        ul = $(
          '<ul class="list-inline mega-menu-content">\n' +
          '<li class="sec-level-item">\n' +
          '<a href="javascript:void(0);"">\n' +
          (menuItem.icon ? '<i class="menuItem.icon"></i>\n' : '\n') +
          '<label data-ng-bind="menuItem.name"></label>\n' +
          '</a>\n' +
          '</li>\n' +
          '</ul>'
        )
        $('label', ul).html(menuItem.name)
        container.append(ul)
      }

      if (level === 1) {
        ul = $(
          '<ul class="sub-mega-menu-content">\n' +
          '        <li class="trd-level-item">\n' +
          '<a href="javascript:void(0);">\n' +
          '<span class="sub-mega-menu-content-value"></span>\n' +
          ((menuItem.children && menuItem.children.length) ? '                <b class="caret right"></b>\n' : '\n') +
          '</a>\n' +
          '</li>\n' +
          '</ul>'
        )
        $('.sub-mega-menu-content-value', ul).html(menuItem.name)
        $(container.children()[order[0]]).append(ul);
      }

      if (level === 2) {
        ul = $(
          '<ul class="ulti-mega-menu-content">\n' +
          '                <li class="fth-level-item">\n' +
          '<a href="javascript:void(0);">\n' +
          '<span class="ulti-mega-menu-content-value"></span>\n' +
          '</a>\n' +
          '</li>\n' +
          '</ul>'
        )
        $('.ulti-mega-menu-content-value', ul).html(menuItem.name)
        // console.log(order, $($(container.children()[order[0]])))
        ul.hide()
        $($($(container.children()[order[0]]).children()[order[1] + 1])).append(ul)
      }

      $('a', ul).click(function () {
        if (level === 1) {
          menuItem.isCollapse = !menuItem.isCollapse
          menuItem.isCollapse ? $('b', ul).removeClass('right') : $('b', ul).addClass('right')
          menuItem.isCollapse ? $('.ulti-mega-menu-content', ul).show() : $('.ulti-mega-menu-content', ul).hide()
        }
        selectMegaMenuItem(menuItem)
      })

    }

  }


  // 深度优先遍历树
  function treenavIterator(data, attr, value) {
    function ti(data, index, level, arr) {
      var node = data;
      var children = node.children;
      if (!(children && children.length)) {
        return;
      }
      var a = [].concat(arr)
      while (index < children.length) {
        a[level] = index
        if (attr instanceof Function) {
          attr(children[index], level, index, a);
        } else {
          children[index][attr] = value;
        }
        ti(children[index], 0, level + 1, a);
        index++;
      }
    }

    ti(data, 0, 0, []);
  }

  function selectMegaMenuItem(menuItem) {
    // console.log('selectMegaMenuItem =>', menuItem)
    if(!(menuItem.children && menuItem.children.length)){
      vm.onMenuItemSelected(menuItem)
    }
  }

  function getMenuData () {
    return scope.menuData
  }

  global.mainController = {
    rendMenuItem: rendMenuItem,
    selectMegaMenuItem: selectMegaMenuItem,
    getMenuData: getMenuData
  }

  vm = global.mainController

})(window)